package com.heima.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {

    @Test
    public void testSendMsg() throws InterruptedException, ExecutionException {
        //2. 通过idea的提示创建配置对象 并完成kafka的配置
        Properties properties = new Properties();
        //配置kafka的ip和端口
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //配置key的序列号
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 3);
        //配置数据同步
        properties.put(ProducerConfig.ACKS_CONFIG, "1");
        //设置消息的压缩格式
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");

        //1. 创建Kafka 生产者的核心对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
       /* for (int i=0; i<10; i++){
            ProducerRecord<String, String> record = new ProducerRecord<>("itcast", "java" + i, "heima" + i);
            producer.send(record);
            TimeUnit.MILLISECONDS.sleep(50);
        }*/

        //生产者同步获取服务器返回的结果
        /*ProducerRecord<String, String> record = new ProducerRecord<>("itcast", "java", "heima");
        RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());*/

        /*//生产者异步获取服务器返回的结果
        ProducerRecord<String, String> record = new ProducerRecord<>("itcast-topic-input", "java", "hello world");
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(null != e){
                    e.printStackTrace();
                }

                System.out.println(recordMetadata.offset());
            }
        });*/

        ProducerRecord<String, String> record = new ProducerRecord<>("itcast-topic-input", "java", "hello heima");
        producer.send(record);

        ProducerRecord<String, String> record1 = new ProducerRecord<>("itcast-topic-input", "java", "hello kafka");
        producer.send(record1);

        //4. 关闭生产者
        producer.close();
    }
}
